const express = require('express');
const router = express.Router();
const { asyncHandle } = require('../getSendResult');
const {
    addAdminUser,
    findAdminUsers,
    deleteAdminUser,
    vagueFindAllAdminusers,
    vagueFindAdminUsers,
    deleteManyAdminUser,
    getAllFolder,
    getAllFiles,
    HomeTaskToday
} = require('../../services/adminUser');
const moment = require('moment');

// 笔记管理后台的home页和user页的api写在同一个文件

// 添加被管理用户
router.post('/addAdminUser', asyncHandle(
    async (req, res, next) => {
        const id = req.body.id;
        const username = req.body.username;
        const userId = req.id;
        return await addAdminUser(id, username, userId);
    }
))

// 获取管理员下管理的用户
router.get('/findAdminUsers', asyncHandle(
    async (req, res, next) => {
        const id = req.id;
        return await findAdminUsers(id);
    }
))
// 模糊查询管理员下管理的用户,通过关键字username查询
router.get('/vagueFindAdminUsers', asyncHandle(
    async (req, res, next) => {
        const userId = req.id;
        const username = req.query.username;
        return await vagueFindAdminUsers(userId, username);
    }
))

// 删除用户
router.get('/deleteAdminUser', asyncHandle(
    async (req, res, next) => {
        const id = req.query.id;
        return await deleteAdminUser(id);
    }
))

// 删除多个用户
router.get('/deleteManyAdminUser', asyncHandle(
    async (req, res, next) => {
        const idArr = req.query.idArr;
        return await deleteManyAdminUser(idArr);
    }
))

// 模糊查询需要添加的用户
router.get('/vagueFindAllAdminusers', asyncHandle(
    async (req, res, next) => {
        const username = req.query.username;
        return await vagueFindAllAdminusers(username);
    }
))


/**
 * 文件数据用于柱状图的数据
 * {
 *    filesTotal: 文件总数
 *    filesAverage: 文件平均数
 *    documents: 文档数量
 *    brainMaps: 脑图数量
 *    tables: 表格数量
 * }
 */
router.get('/histogramFilesData', asyncHandle(
    async (req, res, next) => {
        // 获取被管理用户的所有id,数组
        const id = req.id;
        // console.log('登入id',id);
        let idArr = await findAdminUsers(id);
        idArr = idArr.map((item) => item.selfId);

        // 通过被管理用户的所有id获取所有的文件夹id
        let folders = await getAllFolder(idArr);
        let foldersIdArr = folders.map((item) => item.id);
        if (foldersIdArr.length < 1) {
            return null; //如果没有文件夹
        }

        //通过文件夹id获取所有的文件
        let files = await getAllFiles(foldersIdArr);
        if (files.length < 1) {
            return null; //没有文件
        }

        const documentsData = files.filter((item) => {
            if (item.type == '1') {
                return item;
            }
        })
        const brainMapsData = files.filter((item) => {
            if (item.type == '2') {
                return item;
            }
        })
        const tablesData = files.filter((item) => {
            if (item.type == '3') {
                return item;
            }
        })
        const filesAverageData = files.length / 3;
        return {
            filesTotal: files.length,
            filesAverage: filesAverageData.toFixed(3),
            documents: documentsData.length,
            brainMaps: brainMapsData.length,
            tables: tablesData.length,
        };

    }
))


/**
 * 首页折线图数据
 * returns 
 * {
 *      nearlyTenDaysArr:[],
 *      nearlyTenDaysFileDatas:{
 *         文档:[1,2,3,4,5,6,7,8,9,10],
 *         脑图:[1,2,3,4,5,6,7,8,9,10],
 *         表格:[1,2,3,4,5,6,7,8,9,10],
 *      }
 * }
 */
router.get('/lineChartFileData', asyncHandle(
    async (req, res, next) => {
        // 获取被管理用户的所有id,数组
        const id = req.id;
        // console.log('登入id',id);
        let idArr = await findAdminUsers(id);
        idArr = idArr.map((item) => item.selfId);

        // 通过被管理用户的所有id获取所有的文件夹id
        let folders = await getAllFolder(idArr);
        let foldersIdArr = folders.map((item) => item.id);
        if (foldersIdArr.length < 1) {
            return null; //如果没有文件夹
        }

        //通过文件夹id获取所有的文件
        let files = await getAllFiles(foldersIdArr);
        if (files.length < 1) {
            return null; //没有文件
        }
        // 获取十天前的日期
        let nearlyTenDays = moment().subtract(10, 'days');
        // 创建近十天的日期的数组
        let nearlyTenDaysArr = [];
        let nearlyTenDaysFileDatasClassification = {};
        for (let i = 9; i >= 0; i--) {
            let day = moment().subtract(i, 'days');
            let YDM = moment(day).format('YYYY-MM-DD');
            nearlyTenDaysArr.push(YDM);
            nearlyTenDaysFileDatasClassification[YDM] = {
                documents: [],
                brainMaps: [],
                tables: [],
            }
        }
        // 2021-08-21 11:10:22
        // 筛选近十天创建的数据
        let nearlyTenDaysFileDatas = files.filter((item) => {
            return moment(item.creatiedTime).isAfter(nearlyTenDays, 'day');
        })
        // 按时间把数据分类
        if (nearlyTenDaysArr.length > 0 && nearlyTenDaysFileDatas.length > 0) {
            for (let i = 0; i < nearlyTenDaysArr.length; i++) {
                for (let j = 0; j < nearlyTenDaysFileDatas.length; j++) {
                    if (nearlyTenDaysArr[i] == moment(nearlyTenDaysFileDatas[j].creatiedTime).format('YYYY-MM-DD')) {
                        // console.log(moment(nearlyTenDaysFileDatas[j].creatiedTime).format('YYYY-MM-DD'));
                        if (nearlyTenDaysFileDatas[j].type === '1') {
                            nearlyTenDaysFileDatasClassification[nearlyTenDaysArr[i]].documents.push(nearlyTenDaysFileDatas[j])
                        }
                        if (nearlyTenDaysFileDatas[j].type === '2') {
                            nearlyTenDaysFileDatasClassification[nearlyTenDaysArr[i]].brainMaps.push(nearlyTenDaysFileDatas[j])
                        }
                        if (nearlyTenDaysFileDatas[j].type === '3') {
                            nearlyTenDaysFileDatasClassification[nearlyTenDaysArr[i]].tables.push(nearlyTenDaysFileDatas[j])
                        }
                    }
                }
            }
        }
        // nearlyTenDaysArrLength 需要请求的数据格式
        let nearlyTenDaysArrLength = {
            documents: [],
            brainMaps: [],
            tables: [],
        }
        for (let key in nearlyTenDaysFileDatasClassification) {
            nearlyTenDaysArrLength.documents.push(nearlyTenDaysFileDatasClassification[key].documents.length);
            nearlyTenDaysArrLength.brainMaps.push(nearlyTenDaysFileDatasClassification[key].brainMaps.length);
            nearlyTenDaysArrLength.tables.push(nearlyTenDaysFileDatasClassification[key].tables.length);
        }
        return {
            nearlyTenDaysArr,
            nearlyTenDaysArrLength
        }

    }
))

/**
 * 首页今日任务数据
 * return {
 *      {
        "pieChartData": {
            "total": 5,
            "done": 3,
            "undone": 2
        },
        "userCompletionRate": [
            {
                "user": "bbbb",
                "completionRate": "0.67"
            },
            {
                "user": "root",
                "completionRate": "0.50"
            }
        ]
    }
 * }
 */
router.get('/HomeTaskToday', asyncHandle(
    async (req, res, next) => {
        // 获取被管理用户的所有id,数组
        const id = req.id;
        let userArr = await findAdminUsers(id);
        let idArr = userArr.map((item) => item.selfId);

        // 通过被管理用户的所有id查询今日任务
        let HomeTaskTodayData = await HomeTaskToday(idArr);

        HomeTaskTodayData = HomeTaskTodayData.filter((item) => {
            return moment(item.creatiedTime).isSame(new Date(), 'day');
        })

        // 饼图的数据
        let pieChartData = {
            total: HomeTaskTodayData.length, //全部
            done: [], //完成
            undone: [], //未完成
        }
        // 用户完成情况
        let userCompletion = {};
        HomeTaskTodayData.forEach((item) => {
            if (item.isDone) {
                pieChartData.done.push(item);
            }
            if (!item.isDone) {
                pieChartData.undone.push(item);
            }
            userCompletion[item.userId] = {
                done: [],
                undone: []
            }
        })
        if (JSON.stringify(userCompletion) !== '{}') {
            for (let key in userCompletion) {
                HomeTaskTodayData.forEach((item) => {
                    if (key == item.userId) {
                        if (item.isDone) {
                            userCompletion[key].done.push(item);
                        }
                        if (!item.isDone) {
                            userCompletion[key].undone.push(item);
                        }
                    }
                })
            }
        }
        // 用户完成率
        let userCompletionRate = [];
        for (let key in userCompletion) {
            userCompletionRate.push({
                user: userArr.filter((item) => {
                    if (item.selfId == key) return item
                })[0].username,
                completionRate: (userCompletion[key].done.length / (userCompletion[key].done.length + userCompletion[key].undone.length)).toFixed(2)
            })
        }
        return {
            pieChartData: {
                total: pieChartData.total,
                done: pieChartData.done.length,
                undone: pieChartData.undone.length
            },
            userCompletionRate
        };
    }
))



module.exports = router;